package fei.typhoon.engine.android;

import android.graphics.Canvas;
import fei.typhoon.engine.utils.FeiArrayList;
import fei.typhoon.engine.utils.IFeiView;
import fei.typhoon.engine.utils.ITouchListener;

public class FeiLayer implements IFeiView, ITouchListener {

	protected FeiScreen screen = null;
	private FeiArrayList<FeiSprite> sprites = null;
	private FeiSprite touchSprite = null;

	public FeiLayer() {
		sprites = new FeiArrayList<FeiSprite>();
	}

	public FeiLayer(FeiScreen screen) {
		this();
		this.screen = screen;
	}

	@Override
	public boolean touchDown(float x, float y) {
		boolean processed = false;
		touchSprite = null;
		sprites.resetFore();
		while (sprites.hasFore() && !processed) {
			FeiSprite sprite = sprites.getFore();
			if (sprite != null) {
				processed = sprite.touchDown(x, y);
				if (processed) {
					touchSprite = sprite;
				}
			}
		}
		return processed;
	}

	@Override
	public boolean touchMove(float x, float y) {
		if (touchSprite != null) {
			touchSprite.touchMove(x, y);
			return true;
		}
		return false;
	}

	@Override
	public boolean touchUp(float x, float y) {
		if (touchSprite != null) {
			touchSprite.touchUp(x, y);
			return true;
		}
		return false;
	}

	@Override
	public synchronized void draw(Canvas canvas) {
		sprites.resetNext();
		while (sprites.hasNext()) {
			FeiSprite sprite = sprites.getNext();
			if (sprite != null) {
				sprite.draw(canvas);
			}
		}
	}

	@Override
	public synchronized void destroy() {
		sprites.resetNext();
		while (sprites.hasNext()) {
			FeiSprite sprite = sprites.getNext();
			if (sprite != null) {
				sprite.destroy();
			}
		}
		sprites.clear();
		sprites = null;
		touchSprite = null;
	}

	@Override
	public synchronized void pause() {
		sprites.resetNext();
		while (sprites.hasNext()) {
			FeiSprite sprite = sprites.getNext();
			if (sprite != null) {
				sprite.pause();
			}
		}

	}

	@Override
	public synchronized void resume() {
		sprites.resetNext();
		while (sprites.hasNext()) {
			FeiSprite sprite = sprites.getNext();
			if (sprite != null) {
				sprite.resume();
			}
		}

	}

	public void addSprite(FeiSprite sprite) {
		if (!sprites.contains(sprite)) {
			sprites.add(sprite);
		}
	}

	public void removeSprite(FeiSprite sprite) {
		sprites.remove(sprite);
	}

	public void cleanSprites() {
		sprites.clear();
	}

}
